<template>
  <div class="page-wapper">
    <!-- 权限管理 -->
    <div class="container" v-loading="pageLoading">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">角色名：</div>
            <el-input
              v-model.trim="roleDetail.roleName"
              size="small"
              placeholder="请输入"
              :disabled="
                disabledRoleNameList.includes(roleDetail.roleName) ||
                !$hasPermission($permission.PERMISSION_SAVE_OR_UPDATE)
              "
            ></el-input>
          </div>

          <div class="filter_item">
            <div class="label">所属机构：{{ roleDetail.orgName }}</div>
            <!-- <el-input
              v-model="roleDetail.orgName"
              disabled
              size="small"
            ></el-input> -->
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              v-if="$hasPermission($permission.PERMISSION_SAVE_OR_UPDATE)"
              size="mini"
              :loading="saveBtnLoading"
              type="primary"
              @click="onSave"
            >
              保存
            </el-button>
            <el-button size="mini" @click="goBack"> 返回 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :checkbox-config="{
            checkField: 'checked',
            trigger: 'row',
            checkMethod: tableCheckMethod,
          }"
          :row-style="rowStyle"
          :scroll-y="{ enabled: false }"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          highlight-hover-row
          highlight-current-row
          class="xTable"
          @checkbox-change="checkboxChange"
          @checkbox-all="checkboxAll"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>

          <vxe-column
            field="label"
            title="模块"
            width="200"
            align="left"
            header-align="center"
          ></vxe-column>

          <vxe-column
            title="权限名称"
            align="left"
            min-width="300"
            header-align="center"
          >
            <template #default="{ row }">
              <el-checkbox-group
                v-model="row.checkedList"
                @change="handleCheckedChange(row)"
                @click.stop=""
                :disabled="
                  !$hasPermission($permission.PERMISSION_SAVE_OR_UPDATE)
                "
              >
                <el-checkbox
                  v-for="item in row.list"
                  :key="item.value"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  getCurrentInstance,
  toRefs,
  onActivated,
  computed,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";

const initRoleDetail = () => {
  return {
    id: null,
    roleName: null,
    orgId: null,
    orgName: null,
    permissions: null,
    asUse: false,
  };
};

export default {
  name: "PermissionManage",
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const $permission = proxy.$permission;
    const $hasPermission = proxy.$hasPermission;
    const route = useRoute();
    const router = useRouter();
    const store = useStore();

    // const userInfo = computed(() => store.state.user.userInfo);

    const pageLoading = ref(false);

    const saveBtnLoading = ref(false);

    const roleDetail = reactive(initRoleDetail());

    // 初始化需要禁用的角色名
    const disabledRoleNameList = ref([]);

    const tableState = reactive({
      xTable: null,
      tableData: [],
      tableLoading: false,
    });

    // 获取角色所有信息
    const getRoleDetail = () => {
      if (!route.query.id) {
        pageLoading.value = false;
        return console.error("getRoleDetail error: id 不能为空！");
      }
      pageLoading.value = true;
      getById(route.query.id)
        .then((res) => {
          pageLoading.value = false;
          const data = res.data;
          if (data) {
            Object.keys(roleDetail).forEach((key) => {
              roleDetail[key] = data[key];
            });
            if (roleDetail.permissions) {
              const rolePermissionList = roleDetail.permissions;
              // 权限回显
              tableState.tableData.forEach((item) => {
                const checkedList = [];
                item.list.forEach((cell) => {
                  if (rolePermissionList.includes(cell.value)) {
                    checkedList.push(cell.value);
                  }
                });
                item.checkedList = checkedList;
                handleCheckedChange(item);
              });
            } else {
              // 重置
              tableState.tableData.forEach((item) => {
                item.checkedList = [];
                handleCheckedChange(item);
              });
            }
          } else {
            ElMessage.error("获取角色信息为空");
          }
        })
        .catch((err) => {
          pageLoading.value = false;
          console.error("getRoleDetail error: ", err);
        });
    };

    // 获取角色详情
    const getById = (id) => {
      return new Promise((resolve, reject) => {
        $api.role
          .getById({
            id,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.error("getById error: ", err);
            reject(err);
          });
      });
    };

    // 获取所有权限列表
    const getPermissionAll = () => {
      pageLoading.value = true;
      $api.permission
        .getPermissionAll()
        .then((res) => {
          pageLoading.value = false;
          const allPermissions = res.data.permissionList;
          // let permissionList = [];
          // if (proxy.$isSupperAdmin()) {
          //   permissionList = allPermissions.map((item) => {
          //     return {
          //       ...item,
          //       valueList: item.value.split(":"),
          //     };
          //   });
          // } else {
          //   res.data.permissionList.forEach((item) => {
          //     if (userInfo.value.permissions.includes(item.value)) {
          //       item.valueList = item.value.split(":");
          //       permissionList.push(item);
          //     }
          //   });
          // }
          const permissionList = allPermissions.map((item) => {
            return {
              ...item,
              valueList: item.value.split(":"),
            };
          });
          const permissionModuleList = res.data.permissionModuleList;
          permissionModuleList.forEach((item) => {
            item.checked = false;
            item.checkedList = [];
            item.list = [];
            permissionList.forEach((cell) => {
              if (item.value === cell.valueList[0]) {
                item.list.push(cell);
              }
            });
          });
          tableState.tableData = permissionModuleList.filter(
            (item) => item.list.length
          );
          getRoleDetail();
        })
        .catch((err) => {
          pageLoading.value = false;
          console.error("getPermissionAll error: ", err);
        });
    };

    // const getPermissionAll = () => {
    //   pageLoading.value = true;
    //   $api.permission
    //     .getPermissionAll()
    //     .then((res) => {
    //       // pageLoading.value = false;
    //       const permissionList = res.data.permissionList.map((item) => {
    //         return {
    //           ...item,
    //           valueList: item.value.split(":"),
    //         };
    //       });
    //       const permissionModuleList = res.data.permissionModuleList;
    //       permissionModuleList.forEach((item) => {
    //         item.checked = false;
    //         item.checkedList = [];
    //         item.list = [];
    //         permissionList.forEach((cell) => {
    //           if (item.value === cell.valueList[0]) {
    //             item.list.push(cell);
    //           }
    //         });
    //       });
    //       tableState.tableData = permissionModuleList;
    //       console.log("permissionModuleList ==>", permissionModuleList);
    //       getRoleDetail();
    //     })
    //     .catch((err) => {
    //       pageLoading.value = false;
    //       console.error("getPermissionAll error: ", err);
    //     });
    // };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableState.tableData[rowIndex].checked) {
        return {
          backgroundColor: "pink",
        };
      }
    };

    const handleCheckedChange = (row) => {
      const checkedCount = row.checkedList.length;
      row.checked = checkedCount === row.list.length;
    };

    const checkboxChange = ({ row }) => {
      if (row.checked) {
        row.checkedList = row.list.map((item) => item.value);
      } else {
        row.checkedList = [];
      }
    };

    const checkboxAll = ({ checked }) => {
      if (checked) {
        tableState.tableData.forEach((item) => {
          item.checkedList = item.list.map((cell) => cell.value);
        });
      } else {
        tableState.tableData.forEach((item) => {
          item.checkedList = [];
        });
      }
    };

    const onSave = () => {
      tableState.tableLoading = true;
      let permissionList = [];
      tableState.tableData.forEach((item) => {
        permissionList = permissionList.concat(item.checkedList);
      });
      $api.role
        .saveOrUpdate({
          ...roleDetail,
          permissions: permissionList,
        })
        .then((res) => {
          ElMessage.success("保存成功！");
          getRoleDetail();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    const goBack = () => {
      // 关闭当前tag标签
      const index = store.state.tagsList.findIndex(
        (item) => item.fullPath === route.fullPath
      );
      store.commit("delTagsItem", { index });
      router.go(-1);
    };

    // 获取初始化的角色名列表
    const listInitRoleName = () => {
      $api.role
        .listInitRoleName({})
        .then((res) => {
          disabledRoleNameList.value = res.data || [];
        })
        .catch((err) => {
          console.error("listInitRoleName error: ", err);
        });
    };

    // 列表勾选行的禁用
    const tableCheckMethod = ({ row }) => {
      return $hasPermission($permission.PERMISSION_SAVE_OR_UPDATE);
    };

    /**
     * 初始化
     */
    getPermissionAll();
    listInitRoleName();

    onActivated(() => {
      if (tableState.tableData.length) {
        getRoleDetail();
      }
    });

    return {
      pageLoading,
      handleCheckedChange,
      rowStyle,
      checkboxChange,
      checkboxAll,
      onSave,
      goBack,
      saveBtnLoading,
      roleDetail,
      disabledRoleNameList,
      tableCheckMethod,
      ...toRefs(tableState),
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}
</style>
